#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
#include <math.h>
#include <string.h>
#include "rgatest.hpp"
#include "RgaUtils.h"
#include "dma_alloc.h"

int rga_imgCvtcolor(_IMGINFO src, _IMGINFO dst)
{
    struct timeval start, end;
    float timeuse = 0.0f;
    int ret = imcheck(src.buffer, dst.buffer, src.rect, dst.rect);
    if (ret != IM_STATUS_NOERROR) {
        printf("%d, check error! %s\n", __LINE__, imStrError((IM_STATUS)ret));
        printf("src %dx%d  %d\n", src.buffer.width, src.buffer.height, src.buffer.format);
        return -1;
    }
    //gettimeofday(&start, NULL);
    ret = imcvtcolor(src.buffer, dst.buffer, src.buffer.format, dst.buffer.format);
    if (ret != IM_STATUS_SUCCESS) {
        printf("%d, imcvtcolor failed! %s\n", __LINE__, imStrError((IM_STATUS)ret));
        return -1;
    }
    //gettimeofday(&end, NULL);
    //timeuse = 1000 * (end.tv_sec - start.tv_sec) + (float)(end.tv_usec - start.tv_usec)/1000;
    //printf("imcvtcolor .... cost time %0.3f ms\n", timeuse);
    //printf("dst %dx%d  %d\n", dst.buffer.width, dst.buffer.height, dst.buffer.format);
    return 0;
}

int rga_cvtcolor(_IMGINFO imgSrc, _IMGINFO imgDst)
{
    int src_dma_fd, dst_dma_fd;
    int type = 0;
    int ret = 0;
    int src_buf_size, dst_buf_size;

    char* src_buf = NULL;
    char* dst_buf = NULL;
    type = MODE_CVTCOLOR; 
    src_buf_size = imgSrc.w * imgSrc.h * get_bpp_from_format(imgSrc.format);
    dst_buf_size = imgDst.w * imgDst.h * get_bpp_from_format(imgDst.format);
    //printf("src:%dx%d %d  dst:%dx%d  %d\n", imgSrc.w, imgSrc.h, src_buf_size, imgDst.w, imgDst.h, dst_buf_size);
    imgSrc.handle = importbuffer_virtualaddr(imgSrc.imgData, src_buf_size);
    if (imgSrc.handle == 0) {
        printf("Failed to import virtualaddr for src channel! %s\n", imStrError());
        return -1;
    }
    imgDst.handle = importbuffer_virtualaddr(imgDst.imgData, dst_buf_size);
    if (imgDst.handle == 0) {
        printf("Failed to import virtualaddr for dst channel! %s\n", imStrError());
        return -1;
    }
    imgSrc.buffer = wrapbuffer_handle(imgSrc.handle, imgSrc.w, imgSrc.h, imgSrc.format);
    imgDst.buffer = wrapbuffer_handle(imgDst.handle, imgDst.w, imgDst.h, imgDst.format);
    if (imgSrc.buffer.width == 0 || imgDst.buffer.width == 0) {
        printf("%s, %s", __FUNCTION__, imStrError());
        return -1;
    }
    ret = rga_imgCvtcolor(imgSrc, imgDst);
    if (ret != 0)
    {
        printf("rga_imgCvtcolor error %d\n", ret);
    }
    releasebuffer_handle(imgSrc.handle);
    releasebuffer_handle(imgDst.handle);
    return ret;
}